package com.edu.servlet;

import com.edu.service.impl.productOrderServiceImpl;
import com.edu.entity.User;
import com.edu.service.productOrderService;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/shipOrder")
public class ShipOrderServlet extends HttpServlet {
    private productOrderService orderService = new productOrderServiceImpl();
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        // 测试阶段：硬编码卖家ID为1
    	HttpSession session = request.getSession();
		User u = (User) session.getAttribute("logInUser");
        Integer sellerId = u.getUserid();
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            int orderId = Integer.parseInt(request.getParameter("orderId"));
            String trackingNumber = request.getParameter("trackingNumber");
            
            if (trackingNumber == null || trackingNumber.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "快递单号不能为空");
                sendJson(response, result);
                return;
            }
            
            boolean success = orderService.shipOrder(orderId, sellerId, trackingNumber);
            System.out.println(success);
            result.put("success", success);
            if (!success) {
                result.put("message", "发货失败，请重试");
            }
        } catch (NumberFormatException e) {
            result.put("success", false);
            result.put("message", "无效的订单ID");
        }
        
        sendJson(response, result);
    }
    
    private void sendJson(HttpServletResponse response, Object data) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        new ObjectMapper().writeValue(response.getWriter(), data);
    }
}